// 两个链表的第一个公共节点
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */

/**
 * @param {ListNode} headA
 * @param {ListNode} headB
 * @return {ListNode}
 */
var getIntersectionNode = function (headA, headB) {
    let curA = headA;
    let curB = headB;
    let countA = 0, countB = 0;
    while (curA !== null) {
        countA++;
        curA = curA.next;
    }
    while (curB !== null) {
        countB++;
        curB = curB.next;
    }
    let n = countA - countB > 0 ? countA - countB : countB - countA;
    if (countA > countB) {
        [countA, countB] = [countB, countA];
        [headA, headB] = [headB, headA];
    }
    while (n > 0) {
        headB = headB.next;
        n--;
    }
    while (headA && headB){
        if(headB == headA){
            return headB;
        }else{
            headB = headB.next;
            headA = headA.next;
        }
    }
    return null;
};

